{% extends base.html %}

{% block head %}

<link rel="stylesheet" type="text/css" href="/static/lib/webuploader/webuploader.css">
<script type="text/javascript" src="/static/lib/webuploader/webuploader.nolog.min.js"></script>

<style type="text/css">
    .fs-image {
        width: 180px;
    }
    .fs-path {
        padding: 5px;
        box-sizing: border-box;
        background-color: #eee;
    }
    .left {
        float: left;
    }
    .right {
        float: right;
    }
    .checkboxTd {
        width: 20px;
    }
        
    /* 上传文件样式 */
    .progress {
        background-color: #f90;
        color: #fff;
        height: 20px;
        display: none;
        margin-left: 5px;
        border-width: 3px;
    }
    .progress span {
        display: block;
        background-color: #f90;
        color: #fff;
        height: 100%;
    }
    
    .finished-tag {
        color: #fff;
        background-color: green;
        border-width: 3px;
        border-radius: 3px;
        margin-left: 5px;
    }

    #dropArea {
        float: left;
        width: 100%;
        height: 80px;
        line-height: 80px;
        border: 3px dashed silver;
        text-align: center;
        font-size: 36px;
        color: #d3d3d3;
        cursor: pointer;
        box-sizing: border-box;
    }

    tr:hover td {
        background: none;
    }

    tr:hover {
        background-color: #eee;
    }

    .cmd-input {
        width: 100%;
        max-width: 700px;
        background-color: rgb(230, 230, 255);
        border-width: 1px;
        border-style: solid;
        border-color: black;
        font-family: monospace;
        font-size: 16px;
        display: none;
    }

    #uploadFileArea {
        display: none;
    }

    .size-td {
        width: 100px;
    }
    .options-td {
        width: 100px;
    }

    {% if not xconfig.DEV_MODE %}
        .advanced-opt {
            display: none;
        }
    {% end %}

    #controlArea {
        margin-bottom: 5px;
    }

    #result {
        border: 1px solid #ccc;
        padding: 4px;
        background-color: #eee;
        box-sizing: border-box;
        margin: 0px;
        border-top: none;
        font-family: consolas, monospace;
    }

    .panel-title {
        width: 100%;
        border: 1px solid #ccc;
        padding-left: 5px;
        margin-top: 5px;
    }

    .plugin {
        margin-top: 5px;
    }

    .nav-path {
        padding: 5px;
        box-sizing: border-box;
        background-color: #eee;
    }

</style>

    {% set search_action = '/fs_find' %}
    {% set search_placeholder = '搜索文件' %}
{% end %}

{% block search_form %}
<input type="text" name="path" class="hide" value="{{?path}}"/>
{% end %}

{% block body %}

{% init find_key = "" %}
{% set search_category = "fs" %}

<div class="fs-path">
<a href="/fs//">Home</a> /
{% for item in fspathlist %}
    <a href="/fs/{{ item.path }}">{{ item.name }}</a> / 
{% end %}
</div>

<div id="controlArea" class="col-md-12">
    <div class="left">
        <input type="button" class="btn" value="预览图片" id="previewImg"/>
        <input type="button" class="btn" value="新建文件" id="addFile"/>
        <input type="button" class="btn" value="新建文件夹" id="addDirectory"/>
        <input type="button" class="btn" value="重命名" id="renameBtn" 
            message="重命名为">
        <input id="uploadFileBtn" type="button" class="btn" value="上传">
        <!-- <input type="button" class="btn-danger" value="删除" id="deleteFile"/> -->
        <input type="button" class="btn advanced-opt" value="本地浏览" id="openDirectory"/>
        <input type="button" class="link-btn advanced-opt" href="/code/analyze?path={{path}}&recursive=on" value="高级搜索"/>
        <input type="button" class="link-btn advanced-opt" href="/code/lines?path={{path}}&recursive=on" value="统计"/>
        
        {% for item in xconfig.FS_OPT_BTNS %}
            <input type="button" class="link-btn advanced-opt" x-href="{{item.url}}?path={{path}}" value="{{item.name}}"/>
        {% end %}
        <input type="button" x-href="/fs_api/plugins?path={{path}}" 
            onclick="javascript:showIframeDialog('/fs_api/plugins?path={{path}}')"
            value="更多"/>
    </div>
</div>


<div id="uploadFileArea">
    <!-- 文件上传区域 -->
    <div id="uploader-demo">
        <!--用来存放item-->
        <div id="fileList" class="uploader-list"></div>
        <div id="filePicker" class="hide">选择文件</div>
        <div id="dropArea">点击或拖拽上传文件</div>
    </div>
</div>

<hr/>
<div class="col-md-12">
<table class="col-md-12 no-border-table fs-table">
{% for item in filelist %}
    {# 隐藏文件 #}
    {% if xconfig.FS_HIDE_FILES and (item.name[0] == "." or item.name.endswith((".pyc", ".class"))) %}
        {% continue %}
    {% end %}

    {% if not item.name.startswith("._") %}
    <tr>
        <td class="checkboxTd"><input type="checkbox" data-path="{{item.path}}" data-name="{{item.name}}"></td>
        <td>
        {% if item.type == "dir" %}
            <img src="/static/image/folder.gif"/>
            <a href="/fs/{{item.path}}" class="fs-folder">{{item.name}}</a>
        {% else %}
            <a href="/fs/{{item.path}}?token={{token}}" class="fs-file">{{item.name}}</a>

            {% if xutils.is_img_file(item.path) %}
                <div class="fs-image-div" img-src="/fs/{{item.path}}"></div>
            {% end %}

            {% if item.ext == ".txt" %}
                <a class="item-option" href="/tools/bookreader?path={{item.path}}&from=/fs/{{path}}">阅读</a>
            {% end %}

            {% if item.ext == ".db" %}
                <a class="item-option" href="/tools/sql?path={{item.path}}&from=/fs/{{path}}">查看</a>
            {% end %}

            {% if item.ext in (".log", ".sql") %}
                {% comment 以文本形式查看 %}
                <a class="item-option" href="/fs/{{item.path}}?type=text">查看</a>
            {% end %}

            {% if item.ext in xconfig.FS_TEXT_EXT_LIST %}
                <a class="item-option" href="/code/view_source?path={{url_escape(item.path)}}">编辑</a>
            {% end %}

            {% if item.ext in (".md", ".csv") %}
                <a class="item-option" href="/wiki?path={{item.path}}">预览</a>
            {% end %}

            {% if item.ext in (".pdf", ".mp4") %}
                <a class="item-option" href="/tools/iframe_viewer?path={{quote(item.path)}}">预览</a>
            {% end %}
        {% end %}
        </td>
        <td class="size-td">{{item.size}}</td>
        <td class="options-td">
            <!-- {{item.cdate}} -->
            <a href="javascript:removeFile('{{item.path}}')" class="item-option">删除</a>
            <a class="item-option" 
                href="javascript:showIframeDialog('/fs_api/plugins?path={{item.path}}')">更多</a>
        </td>
    </tr>
    {% end %}
{% end %}
</table>

<input type="text" class="cmd-input" placeholder="请输入指令">
</div>

<script type="text/javascript">
    var globalPath = "{{path}}";

    function previewImages() {
        $(".fs-image-div").each(function (index, target) {
            var img = $("<img>").attr("src", $(target).attr("img-src")).addClass("fs-image");
            $(target).append(img);
            img.on("load", function (event) {
                $(target).append($("<span class='fs-image-size'>").text(img[0].naturalWidth + "*" + img[0].naturalHeight));
            });
        })
        $("#previewImg").val("取消预览");
    }

    function togglePreview() {
        var self = this;
        var value = $(self).val();
        if (window.location.hash != '#preview') {
            previewImages();
            window.location.hash = '#preview';
        } else {
            $(".fs-image").remove();
            $(".fs-image-size").remove();
            $(self).val("预览图片");
            window.location.hash = '';
        }  
    }

    $("#previewImg").on("click", togglePreview);

    if (window.location.hash == '#preview') {
        previewImages();
    }

    function createFile(type) {
        var promptMessage = "新建文件";
        var url = "/fs_api/add_file";

        if (type == "directory") {
            promptMessage = "新建文件夹";
            url = "/fs_api/add_dir";
        }
        var fileName = prompt(promptMessage);
        if (fileName && fileName != "") {
            $.post(url, {path: globalPath, filename: fileName}, function (respText) {
                console.log(respText);
                var data = respText;
                if (data.code == "success") {
                    window.location.reload();
                } else {
                    alert(data.message);
                }
            }).fail(function (data) {
                console.log(data);
                alert(data);
            })
        }
    }

    $("#addDirectory").on("click", function (target) {
        createFile("directory");
    });
    $("#addFile").click(function () {
        createFile("file");
    });

    $("#openDirectory").on("click", function () {
        $.post("/system/command/open", {path: "{{path}}"});
    });
    $(".command-btn").on("click", function () {
        var command = $(this).attr("data-command");
        $.get("/system/command", {command: command, path: globalPath});
    })

    function removeFile(path) {
        var conf = confirm("确认删除 '%s' ?".format(path));
        if (!conf) {
            return;
        }
        $.post("/fs_api/remove", {path: path}, function (resp) {
            if (resp.code == "success") {
                location.reload();
            } else {
                alert("删除失败, %s".format(resp.message));
            }
        }).fail(function (resp) {
            console.log(resp);
            alert("删除失败");
        })
    }

    function showPlugins(path) {

    }

    $("#deleteFile").on("click", function () {
        var checked = $(".checkboxTd :checked");
        if (checked.length == 0) {
            alert("请选择文件");
        } else if (checked.length > 1) {
            alert("不支持批量删除");
        } else {
            var name = checked.attr("data-name");
            var path = checked.attr("data-path");
            removeFile(path);
        }
    });

    $("#renameBtn").on("click", function () {
        var checked = $(".checkboxTd :checked");
        if (checked.length == 0) {
            alert("请选择文件");
        } else if (checked.length > 1) {
            alert("不支持批量重命名");
        } else {
            var name = checked.attr("data-name");
            var path = checked.attr("data-path");
            var dirname = "{{path}}";
            var new_name = prompt("重命名为", name);
            if (new_name) {
                $.post("/fs_api/rename", 
                    {dirname: dirname, old_name: name, new_name: new_name}, 
                    function (resp) {
                        if (resp.code == "success") {
                            location.reload();
                        } else {
                            alert("重命名失败, %s".format(resp.message));
                        }
                }).fail(function (resp) {
                    console.log(resp);
                    alert("重命名失败");
                })
            }
        }
    });
    $("#showMoreOptsBtn").click(function (event) {
        $(".advanced-opt").toggle(200);
    });
    $("#uploadFileBtn").click(function () {
        $("#uploadFileArea").toggle(200);
    })

// 文件上传逻辑
var BASE_URL = "/static/lib/webuploader"
$("#target-path").text(location.hash.substr(1)).attr("href", "/fs/" + location.hash.substr(1));
// 初始化Web Uploader
var uploader = WebUploader.create({

    // 选完文件后，是否自动上传。
    auto: true,

    // swf文件路径
    swf: BASE_URL + '/Uploader.swf',

    // 文件接收服务端。
    server: '/fs_upload/range',

    // 选择文件的按钮。可选。
    // 内部根据当前运行是创建，可能是input元素，也可能是flash.
    pick: '#filePicker',

    // 需要分片
    chunked: true,
    // 默认5M
    // chunkSize: 1024 * 1024 * 5,
    chunkSize: 1024 * 1024 * 5,
    // 重试次数
    chunkRetry: 10,
    // 文件上传域的name
    fileVal: "file",
    // 不开启并发
    threads: 1,
    // 关闭压缩选项
    compress: false
});

// 当有文件添加进来的时候
uploader.on( 'fileQueued', function( file ) {
    var $li = $(
            '<div id="' + file.id + '" class="file-item thumbnail">' +
                '<img>' +
                '<div class="info">' + file.name +
                '<span class="progress"></span>' +
                '<span class="finished-tag" id="' + file.id + '-result"></span>' + 
                 '</div>' +
            '</div>'
            ),
        $img = $li.find('img');

    $list = $("#fileList");
    // $list为容器jQuery实例
    $list.append( $li );

    // 创建缩略图
    // 如果为非图片文件，可以不用调用此方法。
    // thumbnailWidth x thumbnailHeight 为 100 x 100
    var thumbnailWidth = 100;
    var thumbnailHeight = 100;
    uploader.makeThumb( file, function( error, src ) {
        if ( error ) {
            $img.replaceWith('<span>不能预览</span>');
            return;
        }

        $img.attr( 'src', src );
    }, thumbnailWidth, thumbnailHeight );
});

// 文件上传过程中创建进度条实时显示。
uploader.on( 'uploadProgress', function( file, percentage ) {
    var $li = $( '#'+file.id ),
        $percent = $li.find('.progress');
    // $percent.css( 'width', percentage * 100 + '%' );
    $percent.show().text( (percentage * 100).toFixed(2) + '%');
});

uploader.on( 'uploadBeforeSend', function (object, data, headers) {
    data.dirname = "{{path}}"
})

// 文件上传成功，给item添加成功class, 用样式标记上传成功。
uploader.on( 'uploadSuccess', function( file ) {
    $( '#'+file.id ).addClass('upload-state-done');
    $( '#'+file.id + "-result" ).text("上传完成");
});

// 文件上传失败，显示上传出错。
uploader.on( 'uploadError', function( file ) {
    var $li = $( '#'+file.id ),
        $error = $li.find('div.error');

    // 避免重复创建
    if ( !$error.length ) {
        $error = $('<div class="error"></div>').appendTo( $li );
    }

    $error.text('上传失败');
});

// 完成上传完了，成功或者失败，先删除进度条。
uploader.on( 'uploadComplete', function( file ) {
    $( '#'+file.id ).find('.progress').remove();
});

uploader.on( 'error', function (file) {
    alert("未知错误" + file);
})

// 必须先禁用所有的拖拽默认行为
$(document).on("dragenter", function (event) {
    event.preventDefault();
})
$(document).on("dragleave", function (event) {
    event.preventDefault();
})
$(document).on("drop", function (event) {
    event.preventDefault();
})
$(document).on("dragover", function (event) {
    event.preventDefault();
})

$("#dropArea").on("drop", function (event) {
    console.log(event);
    event.preventDefault(); //取消默认浏览器拖拽效果 
    var originalEvent = event.originalEvent;
    var fileList = originalEvent.dataTransfer.files; //获取文件对象 
    console.log(fileList);
    if (fileList && fileList.length > 0) {
        uploader.addFile(fileList);
    }
});

$("#dropArea").on("click", function (event) {
    console.log(event);
    event.preventDefault(); //取消默认浏览器拖拽效果 
    $("[name=file]").click();
})


</script>

{% end %}